var mailViewContentScroll;
var mailEditContentScroll;
var autoComplete1;
var autoComplete2;
var autoComplete3;
var pageSize;
var userid;
var mainListScroll1;
var mainListScroll2;
var mainListScroll3;
var mainListScroll4;
var mainListScroll5;
var mainListScroll6;
var mainListScroll7;
var listBodyH = 0;
var topOffSet = 0;
var imgStar0 = "/mobilemode/apps/e-cology/email/imgs/star999.gif";
var imgStar1 = "/mobilemode/apps/e-cology/email/imgs/stareb6100.gif";

var itemKey = "mobilemode_email_mainList_data";
var mainPanelArr = ["mainList_1","mainList_2","mainList_3","mainList_4","mainList_5","mainList_6","mainList_7"];
$(document).ready(function(){
	//FastClick.attach(document.body);
	var userinfo = $("#userinfo");
	userid = userinfo.val();
	
	pageSize = $("#navUl").attr("pagesize");
	$("#navUl li").bind("click", function(){
		var $obj = $(this);
		var title  = $("div",$obj).html();
		$(".pageHeaderLeft").html(title);
		var currentid = $obj.attr("class");
		var befPanelId = $("#navUl").attr("currentpanelid");
		if(befPanelId!=currentid){
			$("#"+befPanelId).addClass("hide").removeClass("currentPanel");
			$("#"+currentid).removeClass("hide").addClass("currentPanel");
			$("#navUl").attr("currentpanelid",currentid);
			var isload = $("#"+currentid).attr("isload");
			$("#"+currentid +".keyword").val("");
			if(isload==null||isload!=1){
				getListData();
			}
		}
	});
	
	unTouch("#mainList_1");
	unTouch("#mainList_2");
	unTouch("#mainList_3");
	unTouch("#mainList_4");
	unTouch("#mainList_5");
	unTouch("#mainList_6");
	unTouch("#mainList_7");
	
	initScroll(1);
	initScroll(2);
	initScroll(3);
	initScroll(4);
	initScroll(5);
	initScroll(6);
	initScroll(7);
	
	loadListByPageLoad();
	$("#detailPanel .pageHeaderTitle").bind("click", function(){
		hideDetailPanel(true);
	});
	
	$("#detailPanelEdit .pageHeaderTitle").bind("click", function(){
		hideDetailPanelEdit(true);
	});
	
	//添加搜索事件绑定
	$(".listSearch img").click(function(event){
		resetAndSearch();
	});
	$(".listSearch input").keyup(function(event){
		var keyCode = event.keyCode;
		if(keyCode == 13){
			resetAndSearch();
		}
	});
	
	$("form[disabledEnterSubmit]").keydown(function(event){
		if(event.keyCode == 13){return false;}
	});
	
	initAutoInput("to");
	initAutoInput("cc");
	initAutoInput("bcc");
	
	$(".pop_menu li").bind("click", function(){
		$("#batchMenu1").removeClass("active");
		var $obj = $(this);
		var mtype = $obj.attr("mtype");
		var currentPanel = $(".currentPanel");
		var ul = $(".mailList",currentPanel);
		var selectBox = $(".boxWarp.selected",ul);
		var len = selectBox.length;
		
		if(mtype=="in"){//新建内部邮件
			toCreateEmail(1);
		}else if(mtype=="out"){//新建外部邮件
			toCreateEmail(-1);
		}else if(mtype=="del"){//删除
			if(len==0){
				showAlertDialog("请选择要删除的邮件！",null,true);
				return;
			}
			showConfirmDialog("确定要删除吗？",function(){
				var ids = "";
				selectBox.each(function(i){
				   ids += ","+$(this).attr("_id");
				});
				if(ids!=""){
					ids = ids.substring(1);
				}
				movetoFolder(ids,-3);//移到草稿箱
			},null)
		}else if(mtype=="delforever"){//永久删除
			if(len==0){
				showAlertDialog("请选择要永久删除的邮件！",null,true);
				return;
			}
			showConfirmDialog("确定要永久删除吗？",function(){
				var ids = "";
				selectBox.each(function(i){
				   ids += ","+$(this).attr("_id");
				});
				if(ids!=""){
					ids = ids.substring(1);
				}
				deleteEmail(ids);//
			},null);
		}else if(mtype=="read"||mtype=="unread"){ //标为已读   //标为未读  
			if(len==0){
				showAlertDialog("请先选择邮件！",null,true);
				return;
			}
			var ids = "";
			selectBox.each(function(i){
			   ids += ","+$(this).attr("_id");
			});
			if(ids!=""){
				ids = ids.substring(1);
			}
			if(mtype=="read"){
				updateStatus(ids,1);
			}else if(mtype=="unread"){
				updateStatus(ids,0);
			}
		}else if(mtype=="star"||mtype=="unstar"){//标星邮件
			if(len==0){
				showAlertDialog("请先选择邮件！",null,true);
				return;
			}
			var ids = "";
			selectBox.each(function(i){
			   ids += ","+$(this).attr("_id");
			});
			if(ids!=""){
				ids = ids.substring(1);
			}
			if(mtype=="star"){
				updateStar(ids,1);
			}else if(mtype=="unstar"){
				updateStar(ids,0);
			}
		}
	});
	
	$("#xgfj")[0].onchange = function(){
		initFile("xgfj");
	};
	getMail();
	initDateTime("startdate");
	initDateTime("enddate");
	$("#status li").bind("click", function(){
		$("#status .checked").removeClass("checked");
		$(this).addClass("checked");
	})
	$("#pageFooter").hide();
	$("#btnFooterEdit").hide();
	initEditor();
	
	var detailEmailId = $("#detailEmailId").val();
	if(!isNaN(detailEmailId)&&detailEmailId>0){
		openDetailByLoad(detailEmailId);
	}
});

function doEditorChange(){
	var html = SQEditor.getHTML();
	if(html=="<p class=\"paragraph\"></p>"||html==""){
		$("#mouldtexteditor").html("<p class=\"paragraph\"><br></p>");
		SQEditor.moveCursorToEnd();
	}
	if(html=="<p class=\"paragraph\"><br></p>"){
		$(".mouldtextMsg").show();
	}else{
		$(".mouldtextMsg").hide();
	}
}

function afterEditorBlur(){
	clickIndex = 0;
	 if($("#detailContentEdit").hasClass("hide")){
		 $("#detailContentEdit").removeClass("hide");
	 }
}

function afterEditorFocus(){
	if(!$("#detailContentEdit").hasClass("hide")){
		 $("#detailContentEdit").addClass("hide");
	 }
}

function showContent1(type){
	if(type==1){
		$("#mailContentDivEdit").hide();
	}else{
		$("#mailContentDivEdit").show();
	}
}

var SQEditor;
var clickIndex = 0;
function initEditor(){
  var div = document.getElementById('mouldtexteditor');
  SQEditor = new Squire( div, {
      blockTag: 'p',
      blockAttributes: {'class': 'paragraph'},
      tagAttributes: {
          ul: {'class': 'UL'},
          ol: {'class': 'OL'},
          li: {'class': 'listItem'},
          a: {'target': '_blank'}
      }
  });
  SQEditor.setHTML("");
  
  div.onclick = function(event){
	  afterEditorFocus();
	  if(clickIndex==0){
		   SQEditor.focus();
	  }
	  clickIndex++;
	  event.stopPropagation();
  }
  $(".mouldtextMsg")[0].onclick = function(event){
	  afterEditorFocus();
	  if(clickIndex==0){
		   SQEditor.focus();
	  }
	  clickIndex++;
	  event.stopPropagation();
  }
  
  $("#detailPanelEdit")[0].onclick = function(){
	  afterEditorBlur();
  }
}

//自动获取邮件
function getMail(){
	var ids =$("#receivemailids").val();
	if(ids=="")  return;
	var ids2 = ids.split(",");
	var len = ids2.length;
	var num = 0;
	for(var i=0;i<ids2.length;i++){
		if(ids2[i]=="") continue;
		var url = "/email/MailOperationGet.jsp?userid="+userid+"&mailAccountId="+ids2[i];
		$.get(url, function(responseText){
			var da = $.parseJSON(responseText);
			if(da){
				var receivedMailNumber = da["receivedMailNumber"];
				if(receivedMailNumber>0){
					num += receivedMailNumber;
				}
				if(i==ids2.length-1&&num>0){
					resetAndSearch();
				}
			}
		});
	}
}

function initFile(mecid){
	var that = this;
	var file = document.getElementById(mecid);
	if(file.value!=""&&file.files && file.files[0]){
		var contentStr = "<div class='mec_refresh_loading' ><div class='spinner'><div class='bounce1'></div><div class='bounce2'></div><div class='bounce3'></div></div></div>";
		showAlertDialog(contentStr,null,false,"附件上传");
		var filefullname = file.files[0].name;
		var reader = new FileReader();
	   	reader.onload = function(evt){
	   		var result = evt.target.result;
	   		if(result.length > (1024 * 20)&&result.indexOf("data:image/")==0){//大于20K的图片进行压缩
	   			var quality =  0.8;
          		var zoom = 0.8;
	   			if(result.length > (1024 * 1000)){
	   				quality =  0.3;
          			zoom = 0.3;
	   			}else if(result.length > (1024 * 500)){
	   				quality =  0.4;
          			zoom = 0.4;
	   			}else if(result.length > (1024 * 100)){
	   				quality =  0.6;
          			zoom = 0.6;
	   			}
	   			
	            scaleImgData(result, quality, zoom, true, function(newResult){
	            	callbackUpload(filefullname,newResult);
	            });
	   		}else{
		   		callbackUpload(filefullname,result);
	   		}
	   	}
	   	reader.readAsDataURL(file.files[0]);
	}
};


function scaleImgData(imgData, quality, zoom, alsoUseJpeg, callbackFn){

	var mime_type = "image/jpeg";
	if(imgData && !alsoUseJpeg){
		var st = imgData.indexOf("data:");
     	var en = imgData.indexOf(";");
     	if(st == 0 && en > st){
     		try{
     			mime_type = imgData.substring("data:".length, en);
     		}catch(e){
     			mime_type = "image/jpeg";
     		}
		}
	}
     
	var tImg = new Image();
	tImg.onload = function(){
		var cvs = document.createElement('canvas');
		//naturalWidth真实图片的宽度
		var w = tImg.naturalWidth;
		var h = tImg.naturalHeight;
		
		var imageWidth = parseInt(w * zoom);
        var imageHeight = parseInt(h * zoom);
                        
		cvs.width = imageWidth;
		cvs.height = imageHeight;
		
		var con = cvs.getContext('2d');
		con.clearRect(0,0,cvs.width,cvs.height);
		con.drawImage(tImg,0,0,imageWidth,imageHeight);
                    
		//var ctx = com.drawImage(tImg, 0, 0);
		var newImageData = cvs.toDataURL(mime_type, quality);
		callbackFn.call(this, newImageData);
	};
	tImg.src = imgData;
};

/**
 * 移动邮件--到目标
 * @param {Object} mailId
 * @param {Object} targetFolder
 */
function movetoFolder(mailId,targetFolder){
	var url = "/mobilemode/apps/e-cology/email/EmailOperation.jsp?userid="+userid+"&operation=moveto";
	url += "&mailId="+mailId+"&movetoFolder="+targetFolder;
	$.get(url, function(responseText){
		resetAndSearch();
	});
}

/**
 * 单条删除
 * @param {Object} mailId
 */
function moveTo(mailId,groupid){
	if(checkLeftIsOpen()){
		return;
	}
	var panel = $("#listpanel"+groupid);
	$("[is_swiped='true']",panel).trigger("swipeRight");
	showConfirmDialog("确定要删除吗？",function(){
		movetoFolder(mailId,-3);
	},null)
}

/**
 * 修改未读、已读
 * @param {Object} mailId
 * @param {Object} status
 */
function updateStatus(mailId,status){
	var url = "/mobilemode/apps/e-cology/email/EmailOperation.jsp?userid="+userid+"&operation=updateStatus";
	url += "&mailId="+mailId+"&status="+status;
	$.get(url, function(responseText){
		resetAndSearch();
	});
}

/**
 * 单条修改未读已读状态
 */
function changeRead(obj,id,groupid){
	if(checkLeftIsOpen()){
		return;
	}
	var panel = $("#listpanel"+groupid);
	$("[is_swiped='true']",panel).trigger("swipeRight");
	var li = $("#li_"+groupid+"_"+id)
	var readflag = $(obj).attr("_readflag");
	//Ru当前为未读
	var status = readflag=="Ru"?1:0;
	var url = "/mobilemode/apps/e-cology/email/EmailOperation.jsp?userid="+userid+"&operation=updateStatus";
	url += "&mailId="+id+"&status="+status;
	$.get(url, function(responseText){
		if(readflag=="Ru"){//变为已读
			$(".Ru",li).removeClass("Ru").addClass("Rr");
			$(obj).attr("_readflag","Rr");
			$(obj).html("标未读");
			if(groupid==1){
				changeMainListData(id,"timingdateClass","Rr");
			}
		}else{
			$(".Rr",li).removeClass("Rr").addClass("Ru");
			$(obj).attr("_readflag","Ru");
			$(obj).html("标已读");
			if(groupid==1){
				changeMainListData(id,"timingdateClass","Ru");
			}
		}
		
	});
}

/**
 * 标星、取消标星
 * @param {Object} mailId
 * @param {Object} status
 */
function updateStar(mailId,star){
	var url = "/mobilemode/apps/e-cology/email/EmailOperation.jsp?userid="+userid+"&operation=updateStar";
	url += "&mailId="+mailId+"&star="+star;
	$.get(url, function(responseText){
		resetAndSearch();
	});
}

/**
 * 单条修改未读已读状态
 */
function changeStar(obj,id,groupid){
	if(checkLeftIsOpen()){
		return;
	}
	var panel = $("#listpanel"+groupid);
	$("[is_swiped='true']",panel).trigger("swipeRight");
	var li = $("#li_"+groupid+"_"+id)
	var star = $(obj).attr("_starflag");
	if(star==1){//改变star的值
		star = 0;
	}else{
		star = 1;
	}
	var url = "/mobilemode/apps/e-cology/email/EmailOperation.jsp?userid="+userid+"&operation=updateStar";
	url += "&mailId="+id+"&star="+star;
	$.get(url, function(responseText){
		if(star==1){//变为标星
			$(".imgStar",li).attr("src",imgStar1);
			$(obj).attr("_starflag",star);
			$(obj).html("取消标星");
			if(!$("#detailPanel").hasClass("hide")){
				$("#pageFooter li.star img").attr("src","/mobilemode/apps/e-cology/email/imgs/1blue_full.gif");
			}
		}else{
			$(".imgStar",li).attr("src",imgStar0);
			$(obj).attr("_starflag",star);
			$(obj).html("标星邮件");
			if(!$("#detailPanel").hasClass("hide")){
				$("#pageFooter li.star img").attr("src","/mobilemode/apps/e-cology/email/imgs/1blue.gif");
			}
		}
		if(groupid==1){
			changeMainListData(id,"starred",star);
		}
	});
	
}

function deleteEmail(mailId){
	var url = "/mobilemode/apps/e-cology/email/EmailOperation.jsp?userid="+userid+"&operation=delete";
	url += "&mailId="+mailId;
	$.get(url, function(responseText){
		resetAndSearch();
	});
}

function deleteEmailSingle(mailId,groupid){
	showConfirmDialog("确定要永久删除吗？",function(){
		deleteEmail(mailId);
	},null)
}

function initAutoInput(id){
	if("to"==id){
		autoComplete1=new AutoComplete(id,[]);
	}else if("cc"==id){
		autoComplete2=new AutoComplete(id,[]);
	}else if("bcc"==id){
		autoComplete3=new AutoComplete(id,[]);
	}
}


var pdFn = function(e){
	e.preventDefault();
};
function unTouch(selector){
	var obj = $(selector);
	if(obj.length>0){
		if(obj[0].addEventListener){
			obj[0].addEventListener('touchmove', pdFn, false);
		}else if(obj[0].attachEvent){
			obj[0].attachEvent("ontouchmove", function (e) { e.preventDefault(); });
		}
	}
}

var isflag = false;
function initScroll(groupid){
	if(listBodyH==0){
		listBodyH = $("#mainList_"+groupid)[0].clientHeight-$(".pageHeader")[0].clientHeight
					-$("#mainList_"+groupid+" div.listSearch")[0].clientHeight;
	}
	$("#"+mainPanelArr[groupid-1]+" .scroll_wrapper").css("height",listBodyH+"px");
	
	var pullDownObj = document.getElementById('pullDown'+groupid);
	$(pullDownObj).show();
	if(topOffSet==0){
		topOffSet = pullDownObj.offsetHeight;
	}
	var scrollObj = new IScroll("#"+mainPanelArr[groupid-1]+" .scroll_wrapper", {
		mouseWheel: true,
		topOffset: topOffSet,
		preventDefault: false
	});
	scrollObj.on('refresh', function () {
		if (pullDownObj.className.match('loading')) {
			pullDownObj.className = '';
			pullDownObj.querySelector('.pullDownLabel').innerHTML = '下拉可以刷新';
		}
	});
		
	scrollObj.on('scrollStart', function () {
		checkLeftIsOpen();
		if(typeof(isBeScrolling) != "undefined"){
			isBeScrolling = true;
		}
	});
	scrollObj.on('scrollMove', function () {
		if (this.y > 50 && !pullDownObj.className.match('flip')) {
			pullDownObj.className = 'flip';
			pullDownObj.querySelector('.pullDownLabel').innerHTML = '释放立即刷新';
			this.minScrollY = 0;
			isflag = true;
		} else if (this.y < 50 && pullDownObj.className.match('flip')) {
			pullDownObj.className = '';
			pullDownObj.querySelector('.pullDownLabel').innerHTML = '下拉可以刷新';
			this.minScrollY = -pullDownOffset;
		}
	});
	
	scrollObj.on('scrollEnd', function () {
		if(isflag){
			isflag = false;
			if (pullDownObj.className.match('flip')) {
				pullDownObj.className = 'loading';
				pullDownObj.querySelector('.pullDownLabel').innerHTML = '正在刷新...';
			}	
			$("."+mainPanelArr[groupid-1]).attr("pageindex",1);
			$("#"+mainPanelArr[groupid-1]+" .moreData_btn").hide();
			getListData();
		}
	});
		
	if(groupid==1){
		mainListScroll1 = scrollObj;
	}else if(groupid==2){
		mainListScroll2 = scrollObj;
	}else if(groupid==3){
		mainListScroll3 = scrollObj;
	}else if(groupid==4){
		mainListScroll4 = scrollObj;
	}else if(groupid==5){
		mainListScroll5 = scrollObj;
	}else if(groupid==6){
		mainListScroll6 = scrollObj;
	}else if(groupid==7){
		mainListScroll7 = scrollObj;
	}
	
}



function swipeListData(groupid){
	var id = "panel"+groupid;
	var $list = $("#list"+id).filter("[swipe='true']");
	if($list.length > 0){
		var type = $list.attr("swipeType");
		if(!type || type == ""){
			type = "1";
		}
		$list.children("li").each(function(){
			var $li = $(this);
			if($li.attr('swipe_event') != "true"){
				
				var bodyTouch = util.toucher($li[0]);
				
				bodyTouch.on('swipeLeft',function(e){
					if(checkLeftIsOpen()){
						return;
					}
					
					//------------iscroll bug修复-------------------
					//当iscroll在maxScrollY的值在0和-topOffSet之间时，向左滚动出错
					var scrollObj;
					if(groupid==1){
						scrollObj = mainListScroll1;
					}else if(groupid==2){
						scrollObj = mainListScroll2;
					}else if(groupid==3){
						scrollObj = mainListScroll3;
					}else if(groupid==4){
						scrollObj = mainListScroll4;
					}else if(groupid==5){
						scrollObj = mainListScroll5;
					}else if(groupid==6){
						scrollObj = mainListScroll6;
					}else if(groupid==7){
						scrollObj = mainListScroll7;
					}
					var maxScrollY = scrollObj.maxScrollY;
					if(maxScrollY>(topOffSet*(-1))&&maxScrollY<0){
						mainListScroll1.maxScrollY = topOffSet*(-1);
					}
					//------------iscroll bug修复-------------------
	
					var $theLi = $(this);
					
					var pdFn = function(e){
						e.preventDefault();
					};
					
					$theLi[0].addEventListener('touchmove', pdFn, false);
					setTimeout(function(){
						$theLi[0].removeEventListener("touchmove", pdFn, false);
					}, 300);
					
					
					//向左滑动时先复原其他已被划出的LI
					$theLi.siblings("[is_swiped='true']").trigger("swipeRight");
					
					var $slideBtnContainer = $(".slideBtnContainer", $theLi);
					var w = $slideBtnContainer.width();
					
					var $table = $theLi.children(".rowContent");
					if(type == "1"){
						$table.css({
							"-webkit-transform" : "translate3d(-"+w+"px, 0, 0)",
							"transform" : "translate3d(-"+w+"px, 0, 0)"
						});
						$slideBtnContainer.addClass("show");
					}else if(type == "2"){
						$slideBtnContainer.addClass("show");
					}
					$theLi.attr("is_swiped", "true");
					
					
					
				});
				
				var rightFn = function(e){
					if(checkLeftIsOpen()){
						return;
					}
					var $theLi = $(this);
					
					var pdFn = function(e){
						e.preventDefault();
					};
					
					$theLi[0].addEventListener('touchmove', pdFn, false);
					setTimeout(function(){
						$theLi[0].removeEventListener("touchmove", pdFn, false);
					}, 300);
					
					var $slideBtnContainer = $(".slideBtnContainer", $theLi);
					var $table = $theLi.children(".rowContent");
					var w = $slideBtnContainer.width();
					
					if(type == "1"){
						$table.css({
							"-webkit-transform" : "translate3d(0, 0, 0)",
							"transform" : "translate3d(0, 0, 0)"
						});
						$slideBtnContainer.removeClass("show");
					}else if(type == "2"){
						$slideBtnContainer.removeClass("show");
					}
					$theLi.removeAttr("is_swiped");
				};
				
				bodyTouch.on('swipeRight', rightFn);
				$li.bind('swipeRight', rightFn)
			}
		});
		
		$list.children("li").attr("swipe_event", "true");
	}
};

var isFirstLoad = true;
/**
 * 重置分页页数，且重新搜索
 */
function resetAndSearch(){
	var navUl = $("#navUl");
	var currentpanelid = navUl.attr("currentpanelid");
	$("#"+currentpanelid+" .moreData_btn").hide();
	var li = $("."+currentpanelid,navUl);
	li.attr("pageindex",1);
	if(isFirstLoad){
		isFirstLoad = false;
	}else{
		$("#"+currentpanelid+" .mec_refresh_loading").show();
	}
	$("#"+currentpanelid+" .nodata_content").hide();
	getListData();
}

function doSearch(){
	var navUl = $("#navUl");
	var currentpanelid = navUl.attr("currentpanelid");
	$("#"+currentpanelid+" .moreData_btn").hide();
	var li = $("."+currentpanelid,navUl);
	li.attr("pageindex",1);
	if(isFirstLoad){
		isFirstLoad = false;
	}else{
		$("#"+currentpanelid+" .mec_refresh_loading").show();
	}
	$("#"+currentpanelid+" .nodata_content").hide();
	getListData(true);
}

/**
 * 加载下一页
 * @param {Object} obj
 * @param {Object} groupid
 */
function pageList(obj,groupid){
	if(checkLeftIsOpen()){
		return;
	}
	
	$(obj).hide();
	var li = $("#navUl .mainList_"+groupid);
	var pageindex = li.attr("pageindex");
	$("#mainList_"+groupid+" .mec_refresh_loading").show();
	li.attr("pageindex",parseInt(pageindex)+1);
	getListData();
}

/**
 * 获取列表数据
 * @flag 是否为高级搜索  true表示为高级搜索
 */
function getListData(flag){
	var navUl = $("#navUl");
	var currentpanelid = navUl.attr("currentpanelid");
	var loading = $("#"+currentpanelid+" .mec_refresh_loading");
	var currentPanel = $("#"+currentpanelid);
	$(".st-pusher").removeClass("currentPanel");
	currentPanel.addClass("currentPanel");
	var li = $("."+currentpanelid,navUl);
	if(currentpanelid=="mainList_7"){//联系人
		var url = "/mobilemode/apps/e-cology/email/EmailOperation.jsp?userid="+userid+"&operation=getMyContactList";
		var pageindex = li.attr("pageindex");
		if(pageindex==1){
			$("#"+currentpanelid+" .mailList li").remove();
		}
		var keyword = $("#"+currentpanelid+" .keyword").val();
		url += "&pageNo="+pageindex+"&pageSize="+pageSize+"&keyword="+keyword;
		$.get(url, function(responseText){
			var data = $.parseJSON(responseText);
			bulidContactList(data,currentpanelid);
			var groupid = $("."+currentpanelid).index()+1;
			rehreshScrollByGroup(groupid);
		});
	}else{
		var folderid = li.attr("folderid");//类型
		var isInternal = li.attr("isInternal");//是否内部
		var star = li.attr("star");//是否标星
		var pageindex = li.attr("pageindex");
		if(pageindex==1){
			$("#"+currentpanelid+" .mailList li").remove();
		}
		var otherParam = "";
		if(flag){//来自高级搜索
			var status = $("#status .checked");
			if(status.length>0&&status.attr("data-value")=="bx"){
				star = 1;
			}
		}
		var url = "/mobilemode/apps/e-cology/email/EmailOperation.jsp?userid="+userid+"&operation=getMailList";
		var param = "&folderid="+folderid+"&isInternal="+isInternal+"&star="+star+"&perpage="+pageSize+"&index="+pageindex+"&sortColumn=senddate&sortType=DESC";
		var keyword = $("#"+currentpanelid+" .keyword").val();
		if(flag){
			param += "&subject="+$("[name=fieldname_title]").val();
			param += "&from="+$("[name=fieldname_from]").val();
			param += "&to="+$("[name=fieldname_to]").val();
			param += "&datetype=6";
			if($("#startdate").val()!=""){
				param += "&startdate="+$("#startdate").val();
			}
			var status = $("#status .checked");
			if(status.length>0){
				if(status.attr("data-value")=="unread"){
					param += "&status=0";
				}else if(status.attr("data-value")=="read"){
					param += "&status=1";
				}
			}
		}else{
			param += "&subject="+keyword;
		}
		url += param;
		var groupid = $("."+currentpanelid).index()+1;
		
		$.get(url, function(responseText){
			var data = $.parseJSON(responseText);
			if(!flag&&pageindex == 1){
				if(li.index()==0){
					var mainListData = {};
					mainListData["timestmp"] = new Date().getTime();
					mainListData["data"] = data;
					mainListData["userid"] = userid;
					localStorage.removeItem(itemKey);
					localStorage.setItem(itemKey, JSON.stringify(mainListData));
				}
			}
			bulidList(data,currentpanelid);
			rehreshScrollByGroup(groupid);
			if(flag){
				doHistoryBack();
			}
		});
	}
}

function rehreshScrollByGroup(groupid){
	if(groupid==1){
		mainListScroll1.refresh();
	}else if(groupid==2){
		mainListScroll2.refresh();
	}else if(groupid==3){
		mainListScroll3.refresh();
	}else if(groupid==4){
		mainListScroll4.refresh();
	}else if(groupid==5){
		mainListScroll5.refresh();
	}else if(groupid==6){
		mainListScroll6.refresh();
	}else if(groupid==7){
		mainListScroll7.refresh();
	}
}

function changeListBox(obj,eve){
	eve.stopPropagation();
	if(checkLeftIsOpen()){
		return;
	}
	if(!$(obj).hasClass("selected")){
		$(obj).addClass("selected")
	}else{
		$(obj).removeClass("selected")
	}
}

function writelog(str){
	if(console){
		console.log("log:"+str);
	}
}

/**
 * 构建列表
 * @param {Object} data 数据
 * @param {Object} currentpanelid  当前被选中的panel的id
 */
function bulidList(data,currentpanelid){
	var groupid = currentpanelid.replace("mainList_","");
	var dataArray = data["datas"];
	var ul = $("#"+currentpanelid+" ul.mailList");
	var navUl = $("#navUl");
	var li = $("."+currentpanelid,navUl);
	var folderid = li.attr("folderid");
	var label = "";
	if(groupid==1||groupid==4||groupid==5||groupid==6){
		label = "发件人:";
	}else if(groupid==2||groupid==3){
		label = "收件人:";
	}
	for(var i=0;i<dataArray.length;i++){
		var json = dataArray[i];
		var id = json["id"];
		var formatesenddate = json["formatesenddate"];
		var title = json["title"];
		var isinternal = json["isinternal"];
		var subjectshow = json["subjectshow"];
		folderid = json["folderid"];
		var timingdateClass = json["timingdateClass"];
		var timingdateLabel = json["timingdateLabel"];
		var attachmentnumber = json["attachmentnumber"];
		var attachHTML = "";
		if(attachmentnumber>0){
			attachHTML = "<div class=\"attachnum\"><img src=\"/mobilemode/apps/e-cology/email/imgs/attachment.gif\"/></div>";
		}
		var readBtn = "";
		if(timingdateClass=="Ru"){//未读s
			readBtn = "标已读";
		}else{
			readBtn = "标未读";
		}
		var starred = json["starred"];
		var starClass = "";
		var starBtn = "";
		var starSrc = "";
		if(starred==1){
			starBtn = "取消标星";
			starClass = "star";
			starSrc = imgStar1;
		}else{
			starred = 0;
			starBtn = "标星邮件";
			starClass = "unstar";
			starSrc = imgStar0;
		}
		var delBtn = "";
		if(groupid==4){
			delBtn = "<div class=\"btnBox\"  style=\"background-color: #d83202;\" onclick=\"deleteEmailSingle("+id+","+groupid+")\">永久删除</div>";
		}else{
			delBtn = "<div class=\"btnBox\"  style=\"background-color: #d83202;\" onclick=\"moveTo("+id+","+groupid+")\">删除</div>";
		}
		
		var html = "<li id=\"li_"+groupid+"_"+id+"\">"
						+"<div class=\"rowContent\">"
					   		+"<div class=\"boxWarp\" _id=\""+id+"\" onclick=\"changeListBox(this,event)\" ><div class=\"status\"></div></div>"
					   		+"<div class=\"detailWarp\" onclick=\"openDetail(this,"+id+","+groupid+","+folderid+",'"+isinternal+"');\" >"
						   		//+"<div class=\"flag\">"+formatesenddate+"</div>"
						   		+"<div class=\"title "+timingdateClass+"\">"+subjectshow+attachHTML+"</div>"
						   		+"<div class=\"contentDesc\">"+label+title+" 发件日期:"+formatesenddate+"</div>"
						   		+"<img id=\"imgStar"+id+"\" class=\"imgStar\" _star=\""+starred+"\" src=\""+starSrc+"\" >"
					   		+"</div>"
						+"</div>"
				   		+"<div class=\"slideBtnContainer\">"
							+"<div class=\"btnContainer2\">"
								+delBtn
								+"<div class=\"btnBox\" id=\"readBtn_"+groupid+"_"+id+"\"  style=\"background-color:#eb6100;\" _readFlag=\""+timingdateClass+"\" onclick=\"changeRead(this,"+id+","+groupid+")\">"+readBtn+"</div>"
								+"<div class=\"btnBox\"  style=\"background-color:#ec8b00;\" _starFlag=\""+starred+"\" onclick=\"changeStar(this,"+id+","+groupid+")\">"+starBtn+"</div>"
							+"</div>"
						+"</div>"
				   +"</li>";
		ul.append(html);
		var h = $("#li_"+groupid+"_"+id)[0].clientHeight;
		$("#li_"+groupid+"_"+id+" .boxWarp").css("height",(h-2)+"px");
	}
	
	if($("#"+currentpanelid+" ul.mailList").height()>0&&$("#"+currentpanelid+" ul.mailList").height()<document.body.scrollHeight-80)
		 $("#"+currentpanelid+" ul.mailList").height(document.body.scrollHeight-80);
	
	var currentPanel = $("#"+currentpanelid);
	var pageindex = li.attr("pageindex");
	var loading = $("#"+currentpanelid+" .mec_refresh_loading");
	loading.hide();
	if(data["datas"].length>0){//存在数据
		var ishavaNext = data["ishavaNext"];
		if(ishavaNext){//控制是否显示加载更多...
			$(".moreData_btn",currentPanel).show();
		}else{
			$(".moreData_btn",currentPanel).hide();
		}
		$(".nodata_content",currentPanel).hide();
	}else{//没有数据
		if(pageindex==1){//第一页
			$(".nodata_content",currentPanel).show();
		}else{
			$(".nodata_content",currentPanel).hide();
		}
	}
	currentPanel.attr("isload","1");
	swipeListData(groupid);
}


/**
 * 构建列表
 * @param {Object} data 数据
 * @param {Object} currentpanelid  当前被选中的panel的id
 */
function bulidContactList(data,currentpanelid){
	var groupid = currentpanelid.replace("mainList_","");
	var dataArray = data["datas"];
	var totalSize = data["totalSize"];
	var ul = $("#"+currentpanelid+" ul.mailList");
	var navUl = $("#navUl");
	var li = $("."+currentpanelid,navUl);
	for(var i=0;i<dataArray.length;i++){
		var json = dataArray[i];
		var id = json["id"];
		var firstname = json["firstname"];
		var mailUserName = json["mailUserName"];
		var mailaddress = json["mailaddress"];
		var html = "<li   id=\"li_"+groupid+"_"+id+"\" onclick=\"toCreateEmail(-1,'"+id+"','"+mailUserName+"','"+mailaddress+"')\" >"
						+"<div class='rowIcon'>"+firstname+"</div>"
						+"<div class='rowContent'>"
					   		+"<div class=\"title\">"+mailUserName+"</div>"
					   		+"<div>"+mailaddress+"</div>"
				   		+"</div>"
				   +"</li>";
		ul.append(html);
	}
	
	var currentPanel = $("#"+currentpanelid);
	var pageindex = li.attr("pageindex");
	var loading = $("#"+currentpanelid+" .mec_refresh_loading");
	loading.hide();
	var isHaveNext = false;
	if(totalSize>(parseInt(pageindex)*pageSize)){
		isHaveNext = true;
	}
	if(data["datas"].length>0){//存在数据
		if(isHaveNext){//控制是否显示加载更多...
			$(".moreData_btn",currentPanel).show();
		}else{
			$(".moreData_btn",currentPanel).hide();
		}
		$(".nodata_content",currentPanel).hide();
	}else{//没有数据
		if(pageindex==1){//第一页
			$(".nodata_content",currentPanel).show();
		}else{
			$(".nodata_content",currentPanel).hide();
		}
	}
	currentPanel.attr("isload","1");
}

function checkLeftIsOpen(){
	hideBatchMenu();
	var isopen = false;
	//当左侧打开时，需要先关闭左侧-- 见bonzo.js
	if($(container).hasClass("st-menu-open")){
		resetMenu();
		document.removeEventListener( eventtype, bodyClickFn );
		document.getElementById("btnMailbox").classList.toggle("is-active");
		isopen = true;
	}
	return isopen;
}

var currentId = 0 ;
function openDetail(obj,id,groupid,folderid,isinternal){
	if(checkLeftIsOpen()){
		return;
	}
	var btn = $("#readBtn_"+groupid+"_"+id);
	var readflag = $(btn).attr("_readflag");
	if(readflag=="Ru"){//邮件未读时，打开邮件，把未读状态转为已读
		changeRead(btn[0],id,groupid);
	}
	var panel = $("#listpanel"+groupid);
	$("[is_swiped='true']",panel).trigger("swipeRight");
	if(folderid==-2){
		toEditEmail(id,isinternal,folderid,4);
		return;
	}
	$("#mailContentDiv .index7 .fieldvalue").html("");
	$("#mailContentDiv .index7 .fieldvalue").load("/mobilemode/apps/e-cology/email/EmailContent.jsp?userid="+userid+"&mailid="+id+"&type=1&t="+new Date().getTime(),function(){
		setTimeout(function(){
			var p = $("#mailContentDiv .index7 .fieldvalue");
			p.css("width","");
			var maxWidth = p.width();
			p.children().each(function(){
				var w = $(this).width();
				if(w>maxWidth){
					maxWidth = w;
				}
			});
			if(maxWidth>$(window).width()-30){
				p.css("width",maxWidth+"px");
			}
			new IScroll("#mailContentDiv .index7", {
				mouseWheel: true,
				eventPassthrough: true,
				scrollX: true,
				scrollY: false,
				preventDefault: false 
			});
		},500);
	});
	
	var url = "/mobilemode/apps/e-cology/email/EmailOperation.jsp?userid="+userid+"&operation=getMailContent";
	var param = "&mailid="+id;
	url += param;
	var detailPanel = $("#detailPanel");
	showDetailPanel();
	if(currentId == id){
		return;
	}
	
	$("#detailContent").hide();
	$("#mailContentDiv").hide();
	$("#detailPanel .mec_refresh_loading").show();
	
	var detailContent = $("#detailContent");
	$(".index3",detailContent).hide();
	$(".index4",detailContent).hide();
	$(".index6",detailContent).hide();
	$(".fjDetail",detailContent).addClass("hide");
	
	var title = $(".title",$(obj)).text();
	$("#detailPanel .index0 .fieldvalue").html(title);
	$.get(url, function(responseText){
		var data = $.parseJSON(responseText);
		buildDetailPage(data);
	});
	currentId = id;
}



function openDetailByLoad(id){
	var folderid = $("#detailFolderid").val();
	var subject = $("#detailSubject").val();
	var isinternal = $("#detailIsinternal").val();
	
	if(folderid==-2){//草稿箱
		toEditEmail(id,isinternal,folderid,4);
		return;
	}
	$("#mailContentDiv .index7 .fieldvalue").html("");
	$("#mailContentDiv .index7 .fieldvalue").load("/mobilemode/apps/e-cology/email/EmailContent.jsp?userid="+userid+"&mailid="+id+"&type=1&t="+new Date().getTime(),function(){
		setTimeout(function(){
			var p = $("#mailContentDiv .index7 .fieldvalue");
			p.css("width","");
			var maxWidth = p.width();
			p.children().each(function(){
				var w = $(this).width();
				if(w>maxWidth){
					maxWidth = w;
				}
			});
			if(maxWidth>$(window).width()-30){
				p.css("width",maxWidth+"px");
			}
			new IScroll("#mailContentDiv .index7", {
				mouseWheel: true,
				eventPassthrough: true,
				scrollX: true,
				scrollY: false,
				preventDefault: false 
			});
		},500);
	});
	
	var url = "/mobilemode/apps/e-cology/email/EmailOperation.jsp?userid="+userid+"&operation=getMailContent";
	var param = "&mailid="+id;
	url += param;
	var detailPanel = $("#detailPanel");
	showDetailPanel();
	
	$("#detailContent").hide();
	$("#mailContentDiv").hide();
	$("#detailPanel .mec_refresh_loading").show();
	
	var detailContent = $("#detailContent");
	$(".index3",detailContent).hide();
	$(".index4",detailContent).hide();
	$(".index6",detailContent).hide();
	$(".fjDetail",detailContent).addClass("hide");
	
	var title = subject;
	$("#detailPanel .index0 .fieldvalue").html(title);
	$.get(url, function(responseText){
		var data = $.parseJSON(responseText);
		buildDetailPage(data);
	});
	currentId = id;
}

function buildDetailPage(da){
	var mailid = da["mailid"];
	var sendfromName = da["sendfromName"];
	var receiverHtml = da["receiverHtml"];
	var senddate = da["senddate"];
	var subject = da["subject"];
	var replayBtn = da["replayBtn"];//回复  
	var replayAllBtn = da["replayAllBtn"];//回复全部
	var forwardBtn = da["forwardBtn"];//转发
	var recallBtn = da["recallBtn"];//撤回
	var disabled = da["disabled"];//已撤回
	var editAgain = da["editAgain"];//再次编辑
	
	var readBcc = da["readBcc"];//是否密送
	var csHTML = da["csHTML"];//抄送
	var fjcount = da["fjcount"];//附件个数
	var attachArr = da["attachArr"];//附件个数
	var isinternal = da["isinternal"];//1表示内部邮件
	var folderid = da["folderid"];//文件夹id
	var starred = da["starred"];//是否标星
	var starClass = "";
	if(starred==1){
		$("#pageFooter li.star img").attr("src","/mobilemode/apps/e-cology/email/imgs/1blue_full.gif");
	}else{
		$("#pageFooter li.star img").attr("src","/mobilemode/apps/e-cology/email/imgs/1blue.gif");
	}
	
	var detailContent = $("#detailContent");
	$(".index1 .fieldvalue",detailContent).html(sendfromName);//发件人
	$(".index2 .fieldvalue",detailContent).html(receiverHtml);//收件人
	if(csHTML!=""){
		$(".index3",detailContent).show();
		$(".index3 .fieldvalue",detailContent).html(csHTML);//抄送人
	}
	if(readBcc){
		var msHTML = da["msHTML"];//密送
		$(".index4",detailContent).show();
		$(".index4 .fieldvalue",detailContent).html(msHTML);
	}
	//密送人
	$(".index5 .fieldvalue",detailContent).html(senddate);//时间
	if(fjcount>0){
		$(".index6",detailContent).show();
		var fjHTML  = "<img src='/mobilemode/apps/e-cology/email/imgs/attach.gif'>"+fjcount+"";
		$(".index6 .fieldvalue",detailContent).html(fjHTML);//附件
		var fjDetail = $(".fjDetail",detailContent).html("");
		for(var i=0;i<attachArr.length;i++){
			var fileId = attachArr[i]["fileId"];
			var fileSizeName = attachArr[i]["fileSizeName"];
			var imgSrc = attachArr[i]["imgSrc"];
			var filenameshow = attachArr[i]["filenameshow"];
			fjDetail.append("<div class='fielddiv' onclick=\"downloads("+fileId+",'"+filenameshow+"')\" ><span class='fieldnamespan'>"+filenameshow+"</span><span class='fieldsizespan'>("+fileSizeName+")</span></div>");
		}
	}else{
		$(".index6",detailContent).hide();
	}
	
	var btnFooter = $("#btnFooter");
	btnFooter.html("");
	var num = 0;
	$("#pageFooter").attr("mailid",mailid);
	$("#pageFooter").attr("folderid",folderid);
	var btnsWarp = $("#pageFooter .btnsWarp");
	btnsWarp.html("");
	if(replayBtn!=""){
		num++;
		btnsWarp.append("<li><div class=\"menuText\" onclick=\"toHideFooterPop();toEditEmail("+mailid+",'"+isinternal+"',"+folderid+",1);\" >"+replayBtn+"</div></li> ");
	}
	
	if(replayAllBtn!=""){
		num++;
		btnsWarp.append("<li><div class=\"menuText\" onclick=\"toHideFooterPop();toEditEmail("+mailid+",'"+isinternal+"',"+folderid+",2);\" >"+replayAllBtn+"</div></li> ");
	}
	
	if(forwardBtn!=""){
		num++;
		btnsWarp.append("<li><div class=\"menuText\" onclick=\"toHideFooterPop();toEditEmail("+mailid+",'"+isinternal+"',"+folderid+",3);\" >"+forwardBtn+"</div></li> ");
	}
	if(editAgain!=""){
		num++;
		btnsWarp.append("<li><div class=\"menuText\" onclick=\"toHideFooterPop();toEditEmail("+mailid+",'"+isinternal+"',"+folderid+",5);\" >"+editAgain+"</div></li> ");
	}
	if(recallBtn!=""){
		num++;
		btnsWarp.append("<li><div class=\"menuText\" onclick=\"toHideFooterPop();recallBackEmail("+mailid+",'"+isinternal+"');\" >"+recallBtn+"</div></li>");
	}
	setTimeout(function(){
		if(num==0){
			btnFooter.hide();
		}else{
			btnFooter.show();
		}
		$("#detailContent").show();
		$("#mailContentDiv").show();
		$("#detailPanel .mec_refresh_loading").hide();
		resetContentHeight(1);
	},100);
}

function toDelEmail(){
	var mailid = $("#pageFooter").attr("mailid");
	var folderid = $("#pageFooter").attr("folderid",folderid);
	if(folderid!=-3){
		showConfirmDialog("确定要删除吗？",function(){
			movetoFolder(mailid,-3);//移到草稿箱
			doHistoryBack();
		},null)
	}else{
		showConfirmDialog("确定要永久删除吗？",function(){
			deleteEmail(mailid);
			doHistoryBack();
		},null)
	}
}

function changeStarDetail(obj){
	var mailid = $("#pageFooter").attr("mailid");
	var navUl = $("#navUl");
	var currentpanelid = navUl.attr("currentpanelid");
	var groupid = currentpanelid.replace("mainList_","");
	var btn = $("#li_"+groupid+"_"+mailid+" .btnBox[_starflag]");
	changeStar(btn,mailid,groupid)
}



function toHideFooterPop(){
	$("#footerBg").addClass("hide");
	$("#footerDiv").addClass("hide");
}

function toShowFooterPop(type,objid,flag){
	var item = $("#footerDiv .footer-item");
	item.html("");
	if(type==1){
		var btnsWarp = $("#pageFooter .btnsWarp");
		item.html(btnsWarp.html());
	}else if(type==2){
		if(objid == 2 || objid == 1){
			item.append("<li><div class=\"menuText\" onclick=\"toHideFooterPop();toCreateEmail(1);\" >新邮件(内部)</div></li>");
		}
		if(objid == 2 || objid == 0){
			item.append("<li><div class=\"menuText\" onclick=\"toHideFooterPop();toCreateEmail(-1);\" >新邮件(外部)</div></li>");
		}
		
		
	}else if(type==3){
		
		var c1 = "";
		var c2 = "";
		var c3 = "";
		if($("#"+objid).val()!=""){
			c1 = " selected";
		}else if($("#"+objid+"dpid").val()!=""){
			c2 = " selected";
		}else if($("#"+objid+"all").val()!=""){
			c3 = " selected";
		}
		
		item.append("<li><div type=\"1\" class=\"menuText"+c1+"\" onclick=\"toHideFooterPop();openBrowserByType(this);\" >人员</div></li>");
		item.append("<li><div type=\"2\" class=\"menuText"+c2+"\" onclick=\"toHideFooterPop();openBrowserByType(this);\" >部门</div></li>");
		if(flag == 1){
			item.append("<li><div type=\"3\" class=\"menuText"+c3+"\" onclick=\"toHideFooterPop();openBrowserByType(this);\" >所有人</div></li>");
		}
	}
	$("#footerBg").removeClass("hide");
	$("#footerDiv").removeClass("hide");
}

/**
 * 重新计算邮件内容的高度
 */
function resetContentHeight(type){
	if(type==1){//邮件查看页面内容高度
		var detailPanel = $("#detailPanel");
		var btnFooter = $("#pageFooter");
		var h = detailPanel[0].clientHeight-btnFooter[0].clientHeight;
		$("#detailPanel .pageBody").css("height",(h)+"px");
	}else{//邮件编辑页面内容高度
		var detailPanel = $("#detailPanelEdit");
		var btnFooter = $("#btnFooterEdit");
		var h = detailPanel[0].clientHeight-btnFooter[0].clientHeight;
		$("#detailPanelEdit .pageBody").css("height",(h)+"px");
	}
}

function toCreateEmail(isinternal,id,name,email){
	if(checkLeftIsOpen()){
		return;
	}
	toEditEmail(-1,isinternal,-1,-1,function(){
		if(isinternal!=1){//从联系人直接进入
			if(id&&name&&email){
				var showname = name+"&lt;"+email+"&gt;";
				var sendtoArr = [{"name":email,"showname":showname}];
				setValueByInput(autoComplete1,sendtoArr);
			}
		}
	});//创建
	
	//处理隐藏域
	$("#folderid").val(-1);
	$("#flag").val(-1);
	$("#mobile_flag").val(-1);
	$("#mailid").val(-1);
	$("#mobile_mailid").val(-1);
	$("#isInternal").val(isinternal);
}

function consoleRow(){
	if($("#detailContentEdit .index3").hasClass("hide")){
		$("#detailContentEdit .index3").removeClass("hide");
		$("#detailContentEdit .index4").removeClass("hide");
		$(".consoleIcon").attr("src","/mobilemode/apps/e-cology/email/imgs/retract01.png");
	}else{
		var isInternal = $("#isInternal");
		if(isInternal==1){
			var internalcc = $("#internalcc").val();
			var internalccdpid = $("#internalccdpid").val();
			var internalccall = $("#internalccall").val();
			
			var internalbcc = $("#internalbcc").val();
			var internalbccdpid = $("#internalbccdpid").val();
			var internalbccall = $("#internalbccall").val();
			if(internalcc==""&&internalccdpid==""&&internalccall==""
					&&internalbcc==""&&internalbccdpid==""&&internalbccall==""){
				$(".consoleIcon").attr("src","/mobilemode/apps/e-cology/email/imgs/retract02.png");
				$("#detailContentEdit .index3").addClass("hide");
				$("#detailContentEdit .index4").addClass("hide");
			}
		}else{
			if($("#cc_div .emailDiv").length==0&&$("#bcc_div .emailDiv").length==0){
				$(".consoleIcon").attr("src","/mobilemode/apps/e-cology/email/imgs/retract02.png");
				$("#detailContentEdit .index3").addClass("hide");
				$("#detailContentEdit .index4").addClass("hide");
			}
		}
	}
}

/**
 * 回复邮件
 */
function toEditEmail(id,isinternal,folderid,flag,callback){
	$("#btnFooterEdit").removeClass("issubmiting");
	$("#olduuids").val("");
	if(!flag){
		flag = -1;
	}
	$("#detailContentEdit").removeClass("hide");
	$("#mailContentDivEdit").show();
	$("#searchDiv").addClass("hideEle");
	SQEditor.blur();
	$("#detailContentEdit .index3").addClass("hide");
	$("#detailContentEdit .index4").addClass("hide");
	$(".consoleIcon").attr("src","/mobilemode/apps/e-cology/email/imgs/retract02.png");
	
	
	$("#mailContentDivEditPre").html("");
	$("#mailContentDivEditPre").load("/mobilemode/apps/e-cology/email/EmailContent.jsp?userid="+userid+"&flag="+flag+"&mailid="+id+"&type=2&t="+new Date().getTime(),function(){
		var mailContent = $("#mailContentDivEditPre").html();
		SQEditor.setHTML(mailContent);
		if(mailContent==""){
			$(".mouldtextMsg").show();
		}else{
			$(".mouldtextMsg").hide();
		}
		var mouldtexteditor = $("#mouldtexteditor");
		setTimeout(function(){
			$("#EmailNew_fengeinput",mouldtexteditor).css("color","red");
		},200);
	});
	$("#subject").css("width",($(window).width()-30-70-20)+"px");
	var detailPanelEdit = $("#detailPanelEdit");
	var url = "/mobilemode/apps/e-cology/email/EmailOperation.jsp?userid="+userid+"&operation=getMailContentEdit";
	var param = "&id="+id+"&folderid="+folderid+"&flag="+flag+"&isInternal="+isinternal;
	url += param;
	$.get(url, function(responseText){
		var data = $.parseJSON(responseText);
		setEditMailVal(data,isinternal);
		
		if(callback){
			callback();
		}
		//处理隐藏域
		$("#folderid").val(-1);
		$("#flag").val(flag);
		$("#mobile_flag").val(flag);
		$("#mailid").val(id);
		$("#mobile_mailid").val(id);
		$("#isInternal").val(isinternal);
		showDetailPanelEdit();
		resetContentHeight(2);
		if($("#to_input").width()>0){
			$("#subject").css("width",($("#to_input").width())+"px");
		}
	});
}



function resetBrowserVal(id){
	$("#"+id).val("");
	$("#"+id+"dpid").val("");
	$("#"+id+"all").val("");
	$("#"+id+"Span").html("");
}

function formateVal(v){
	if(v=="0"){
		v = "";
	}
	return v;
}

function setEditMailVal(d,isinternal){
	var subject = d["subject"];
	var priority = d["priority"];
	
	var toall = d["toall"];
	var toids = d["toids"];//收件人
	var todpids = d["todpids"];
	var toidsname = d["toidsname"];
	var todpidsname = d["todpidsname"];
	
	toids = formateVal(toids);
	toall = formateVal(toall);
	todpids = formateVal(todpids);
	
	
	var currentid = "internalto";
	resetBrowserVal(currentid);
	if(isinternal==1){//内部邮件
		$("#detailContentEdit div.row:not(.same) div.fieldvalue").show();
		$("#detailContentEdit div.row:not(.same) div.fieldvalue1").hide();
	}else{//外部邮件
		$("#detailContentEdit div.row:not(.same) div.fieldvalue").hide();
		$("#detailContentEdit div.row:not(.same) div.fieldvalue1").show();
		var mailAccountArr = d["mailAccountArr"];
		var isHaveChecked = d["isHaveChecked"];
		$("#mailAccountId option").remove();
		var selObj = $("#mailAccountId");
		if(mailAccountArr.length==0){//发件人
			$("#mailAccountId_Msg").show();
			selObj.hide();
		}else{
			 for(var i=0;i<mailAccountArr.length;i++){
				 var mid = mailAccountArr[i]["mid"];
				 var mname = mailAccountArr[i]["mname"];
				 var isselected = mailAccountArr[i]["isselected"];
				 var selStr = isselected?"selected":"";
				 selObj.append("<option value=\""+mid+"\"  "+selStr+" >"+mname+"</option>");
			 }
		}
		
		var sendtoArr = d["sendtoArr"];
		var sendccArr = d["sendccArr"];
		var sendbccArr = d["sendbccArr"];
		setValueByInput(autoComplete1,sendtoArr);
		setValueByInput(autoComplete2,sendccArr);
		setValueByInput(autoComplete3,sendbccArr);
		if(sendccArr.length==0&&sendbccArr.length==0){
			
		}
	}
	if(isinternal==1){//内部邮件
		if(toall=="1"){
			$("#"+currentid+"all").val(toall);
			$("#"+currentid+"Span").html("所有人");
		}else if(toids!=""){
			$("#"+currentid).val(toids);
			$("#"+currentid+"Span").html(toidsname);
		}else if(todpids!=""){
			$("#"+currentid+"dpid").val(todpids);
			$("#"+currentid+"Span").html(todpidsname);
		}
		
	}
	var ccall = d["ccall"];
	var ccids = d["ccids"];//抄送人
	var ccdpids = d["ccdpids"];
	var ccidsname = d["ccidsname"];
	var ccdpidsname = d["ccdpidsname"];
	ccids = formateVal(ccids);
	ccall = formateVal(ccall);
	ccdpids = formateVal(ccdpids);
	
	currentid = "internalcc";
	resetBrowserVal(currentid);
	if(isinternal==1){//内部邮件
		if(ccall=="1"){
			$("#"+currentid+"all").val(ccall);
			$("#"+currentid+"Span").html("所有人");
		}else if(ccids!=""){
			$("#"+currentid).val(ccids);
			$("#"+currentid+"Span").html(ccidsname);
		}else if(ccdpids!=""){
			$("#"+currentid+"dpid").val(ccdpids);
			$("#"+currentid+"Span").html(ccdpidsname);
		}
	}
	
	var bccids = d["bccids"];//密送人
	var bccall = d["bccall"];
	var bccdpids = d["bccdpids"];
	var bccidsname = d["bccidsname"];
	var bccdpidsname = d["bccdpidsname"];
	
	bccids = formateVal(bccids);
	bccall = formateVal(bccall);
	bccdpids = formateVal(bccdpids);
	
	currentid = "internalbcc";
	resetBrowserVal(currentid);
	if(isinternal==1){//内部邮件
		if(bccall=="1"){
			$("#"+currentid+"all").val(bccall);
			$("#"+currentid+"Span").html("所有人");
		}else if(bccids!=""){
			$("#"+currentid).val(bccids);
			$("#"+currentid+"Span").html(bccidsname);
		}else if(bccdpids!=""){
			$("#"+currentid+"dpid").val(bccdpids);
			$("#"+currentid+"Span").html(bccdpidsname);
		}
		
	}
	
	var bccids = d["bccids"];//密送人
	var bccall = d["bccall"];
	var bccdpids = d["bccdpids"];
	
	if(isinternal==1){
		//抄送和密送有值时
		if(!(ccall==""&&ccids==""&&ccdpids==""
				&&bccids==""&&bccall==""&&bccdpids=="")){
			$("#detailContentEdit .index3").removeClass("hide");
			$("#detailContentEdit .index4").removeClass("hide");
			$(".consoleIcon").attr("src","/mobilemode/apps/e-cology/email/imgs/retract01.png");
		}
	}else{
		if($("#cc_div .emailDiv").length>0||$("#bcc_div .emailDiv").length>0){
			$("#detailContentEdit .index3").removeClass("hide");
			$("#detailContentEdit .index4").removeClass("hide");
			$(".consoleIcon").attr("src","/mobilemode/apps/e-cology/email/imgs/retract01.png");
		}
	}
	
	//重要性
	if(priority==""){
		priority = "3";
	}
	$("#priority").val(priority);
	$(".checkboxBtn").removeClass("selected")
	if(priority=="3"){
		$($(".checkboxBtn")[0]).addClass("selected");
	}else{
		$($(".checkboxBtn")[1]).addClass("selected");
	}
	
	
	var accids = d["accids"];//附件
	var accStr = d["accStr"];
	$("#accids").val(accids);
	$("#delaccids").val("");
	$("#accstr").html(accStr);
	relaceDel();
	
	$("#subject").val(subject);
}

/**
 * 替换附件中的“删除”--为图标
 */
function relaceDel(){
	var del = $("#accstr a.del:not(.delicon)");
	del.html("<img src=\"/mobilemode/apps/e-cology/email/imgs/del.png\">").addClass("delicon");
}


/**
 * 转发
 * @param {Object} id
 */
function forwardEmail(id){
	$("#detailPanelEdit .pageHeaderTitle").html("转发");
}

/**
 * 撤回
 * @param {Object} id
 */
function recallBackEmail(id){
	var url = "/mobilemode/apps/e-cology/email/EmailOperation.jsp?userid="+userid+"&operation=recall&mailId="+id;
	$.get(url, function(responseText){
		var data = $.parseJSON(responseText);
		if(data["flag"]){
			showAlertDialog("撤回成功",null,true);
		}else{
			showAlertDialog("撤回失败",null,true);
		}
	});
}

function changeBoxVal(obj,objid,value){
	if(!$(obj).hasClass("selected")){
		$(".checkboxBtn").removeClass("selected");
		$(obj).addClass("selected");
		$("#"+objid).val(value);
	}
}



/**
 * 
 * @param {Object} selector
 * @return {TypeName} 
 */
function createScroll(selector){
	var myScroll = new IScroll(selector, {
	    mouseWheel: true,
		preventDefault: false,
		bounce:false
	});
	return myScroll;
}

function refreshScrollWithImg(scrollObj){
	refreshScroll(scrollObj);
	setTimeout(function(){
		refreshScroll(scrollObj);
	}, 2000);
}

function refreshScroll(scrollObj){
	if(scrollObj){
		scrollObj.refresh();
	}
}

function downloads(fileid,filename){
   	filename=filename?filename:"";
	location = "/download.do?fileid="+fileid+"&filename="+encodeURI(filename)+"&module=-2&scope=-301&form_email=1&download=1";
}

function showFjDetail(){
	var row = $("#detailContent .index6");
	if($(".fjDetail",row).hasClass("hide")){
		$(".fjDetail",row).removeClass("hide")
	}else{
		$(".fjDetail",row).addClass("hide")
	}
	resetContentHeight(1);
	refreshScroll(mailViewContentScroll);
}

/**
 * 隐藏当前页面#detailPanel
 * @param {Object} isBackHistory 是否调用浏览器history.go(-1)
 * 当使用浏览器自己的后退时，无需再调用history.go(-1),如果使用自定义js隐藏时需要调用history.go(-1)
 */
function hideDetailPanel(isBackHistory){
	$("#pageFooter").hide();
	if(isBackHistory){
		doHistoryBack();//使用js的返回时,调用浏览器的返回--会触发popstate
	}else{
		$(".currentPanel").removeClass("hideLeft");
		$(".pageHeader").removeClass("hideLeft");
		$("#detailPanel").addClass("hide");
	}
}

function showDetailPanel(){
	$("#pageFooter").show();
	$("#btnFooterEdit").hide();
	
	$("#detailPanel").removeClass("hide");
	$(".currentPanel").addClass("hideLeft");
	$(".pageHeader").addClass("hideLeft");
	pushHistoryState({url:"a"});
}

/**
 * 隐藏当前页面div
 * @param {Object} isBackHistory 是否调用浏览器history.go(-1)
 */
function hideDetailPanelEdit(isBackHistory){
	$("#btnFooterEdit").hide();
	$("#searchDiv").removeClass("hideEle");
	if(isBackHistory){
		doHistoryBack();
	}else{
		$("#detailPanelEdit").addClass("hide");
		if($("#detailPanel").hasClass("hideLeft")){
			$("#detailPanel").removeClass("hideLeft");
			$("#pageFooter").show();
		}else if($(".currentPanel").hasClass("hideLeft")){
			$(".currentPanel").removeClass("hideLeft");
			$(".pageHeader").removeClass("hideLeft");
			$("#pageFooter").hide();
		}
	}
}

function showDetailPanelEdit(){
	$("#pageFooter").hide();
	$("#btnFooterEdit").show();
	var h = $(".ke-container").height();
	$(".ke-container").parent().css("height",h+"px");
	$("#detailPanelEdit").removeClass("hide");
	if(!$("#detailPanel").hasClass("hide")){
		$("#detailPanel").addClass("hideLeft");
	}else if(!$(".currentPanel").hasClass("hide")){
		$(".currentPanel").addClass("hideLeft");
		$(".pageHeader").addClass("hideLeft");
	}
	pushHistoryState({url:"b"});
}

function doLeftButton(){
	return "BACK";
}

function doHistoryBack(){
	history.go(-1);
}

function doBackPage(){
	if(isOpenBrowser){//如果打开了浏览按钮页面
		if(isUserBrowserOk){//使用浏览框的确定按钮
			isUserBrowserOk = false;
		}
		isOpenBrowser = false;
		if(!$("#browserFrames").hasClass("hide")){
			$("#browserFrames").addClass("hide");
		}
		if($("#detailPanel").hasClass("hideLeft2")){
			$("#detailPanel").removeClass("hideLeft2");
		}
		return 1;
	}
	SQEditor.blur();
	toHideFooterPop();
	hideConfirmDialog();
	hideAlertDialog();
	if(!$("#browserType").hasClass("hide")){
		$("#browserType").addClass("hide");
	}
	if(!$("#detailPanelEdit").hasClass("hide")){
		hideDetailPanelEdit(false);
		return "1";
	}else if(!$("#detailPanel").hasClass("hide")){
		hideDetailPanel(false);
		return "1";
	}else if(!$("#searchDiv").hasClass("hide")){
		$("#searchDiv").addClass("hide");
		$(".currentPanel").removeClass("hideLeft");
		$(".pageHeader").removeClass("hideLeft");
		return "1";
	}
}

$(document).ready(function(){
	setTimeout(function(){
		if (history.pushState) {
			history.replaceState({}, "", location.href);
			window.addEventListener("popstate", function(event) {
				if(event && event.state){
		    		doBackPage();
		    	}else{
		    		doHistoryBack();
		    	}
		    });
		}
	}, 100);
});

function pushHistoryState(state, title, url){
	if(!url){
		url = location.href;
		var timestampReg = /(\?|&)timestamp=\d{13}/;
		var timestampMatches = timestampReg.exec(url);
		if(timestampMatches){
			url = url.replace(timestampMatches[0], "");
		}
		if(url.indexOf("?") != -1){
			url += "&timestamp=" + new Date().getTime();
		}else{
			url += "?timestamp=" + new Date().getTime();
		}
	}
	if(!title){
		title = document.title;
	}
	if(!state || typeof(state) != "object"){
		state = {title:title,url:url};
	}
	
	if(history.pushState){
		history.pushState(state, title, url);
		isNeedBackPage = true;
    }
}


var mbrowser = {
  versions: function () {
  var u = navigator.userAgent, app = navigator.appVersion;
  return {//移动终端浏览器版本信息
   trident: u.indexOf('Trident') > -1, //IE内核
   presto: u.indexOf('Presto') > -1, //opera内核
   webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
   gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
   mobile: !!u.match(/AppleWebKit.*Mobile/i) || !!u.match(/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/), //是否为移动终端
   ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
   android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
   iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
   iPad: u.indexOf('iPad') > -1, //是否iPad
   webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
  };
  } (),
  language: (navigator.browserLanguage || navigator.language).toLowerCase()
}

function callbackUpload(name,data,index) {
	var url = "/mobilemode/apps/e-cology/email/EmailOperation.jsp?userid="+userid+"&operation=getUUID";
	$.get(url, function(responseText){
		var da = $.parseJSON(responseText);
		var uuid = da["uuid"];
		$("#fileuuid").val(uuid);
		if(data) document.getElementById('uploaddata').value = data;
		if(name) document.getElementById('uploadname').value = name;
		document.getElementById("dataForm").submit();
	});
}


function showDocinfo(json){
	$('#uploaddata').val("");
	$('#uploadname').val("");
	var docid = json["docid"];
	var fileuuid = json["fileuuid"];
	var olduuids = $("#olduuids");
	if(olduuids.val().indexOf(fileuuid)!=-1){
		return;
	}else{
		 olduuids.val(olduuids.val()+","+fileuuid);
	}
	
	if(docid>0){
		var htmlStr = json["htmlStr"];
		$("#accstr").append(htmlStr);
		relaceDel();
		var accids=$("#accids").val();
		if(accids==""){
			accids=","+docid+",";
		}else{
			accids=accids+docid+",";
		}
		$("#accids").val(accids);
	}
	$("#xgfj").val("");
	hideAlertDialog();
}


var thisobj;
var fileindex = 0;
function addUpload(e,obj) {
	$("#fileindex").val(fileindex++);
	var index=1;
	thisobj=obj;
	location = "emobile:upload:callbackUpload:"+index+":"+(e.clientY+10)+":clearAppendix";
}

function doDelAcc(id){
	var ids = $("#accids").val();
	ids = ids.replace(","+id+",",",")
	$("#accids").val(ids);
	$("#"+id).remove();
	
	var delids = $("#delaccids").val();
	if(delids!=""){
		delids = delids+","+id;
	}else{
		delids = id;
	}
	$("#delaccids").val(delids);
}

function sendEmail(){
	
}

function setEmailValReal(id){
	$("#"+id).val("");
	var emailDiv = $("#"+id+"_div .emailDiv");
	var values = "";
	for(var i=0;i<emailDiv.length;i++){
		var v = $(emailDiv[i]).attr("email");
		values += ","+v;
	}
	if(values!=""){
		values = values.substring(1);
	}
	$("#"+id).val(values);
}

var btnType = 0;
function saveEmail(type){
	if($("#btnFooterEdit").hasClass("issubmiting")){
		return;
	}
	afterEditorBlur();
	$("#btnFooterEdit").addClass("issubmiting");
	var isInternal = $("#isInternal").val();
	if(isInternal!=1){
		var opt = $("#mailAccountId option");
		if(opt.length==0){
			showAlertDialog("您还未创建邮件账户.",null,true);
			$("#btnFooterEdit").removeClass("issubmiting");
			return;
		}
	}
	if(checkRequired()){
		if(isInternal!=1){//外部邮件
			setEmailValReal("to");
			setEmailValReal("cc");
			setEmailValReal("bcc");
		}
		btnType = type;
		if(type==2){
			$("#folderid").attr("value","-2");//设置为草稿状态
			$("#savedraft").attr("value","1");//只保存到草稿
		}
		var flag = $("#flag").val();
		//在草稿列表打开的   flag  1:回复  2：全部回复   3：转发   4:草稿直接打开
		if(flag!="4"){
		 	$("#mailid").val("");//非草稿状态的邮件不要传递邮件id到后台
		}
		$("#mailContentDivSubmitPre").html($("#mouldtext").val());
		var imgs = $("#mailContentDivSubmitPre img");
		imgs.each(function(){
			var s = $(this).attr("src")
			if(s&&s!=""){
				$(this).attr("submitimgtemp",s);
				this.removeAttribute("src");
			}
		});
		$("#mouldtext").val($("#mailContentDivSubmitPre").html());
		$("#weaver").submit();
	}
}

function checkIsSubmitAndGoBack(){
	if(!$("#detailPanelEdit").hasClass("hide")){
		if($("#btnFooterEdit").hasClass("issubmiting")){
			doHistoryBack();
			$("#btnFooterEdit").removeClass("issubmiting")
		}
	}
}

function doSubmitResult(f){
	var flag = $("#flag").val();
	var submitName = "";
	//在草稿列表打开的   flag  1:回复  2：全部回复   3：转发   4:草稿直接打开
	if(btnType==2){
		if(f=="false"){
			showAlertDialog("草稿保存失败!",function(){
				doHistoryBack();
				setTimeout(function(){
					checkIsSubmitAndGoBack();
				},1000);
			},true)
		}else{
			showAlertDialog("草稿保存成功!",function(){
				doHistoryBack();
				setTimeout(function(){
					checkIsSubmitAndGoBack();
				},1000);
				resetAndSearch();
			},true)
		}
	}else{
		if(f=="false"){
			showAlertDialog("邮件发送失败!",function(){
				doHistoryBack();
				setTimeout(function(){
					checkIsSubmitAndGoBack();
				},1000);
			},true)
		}else{
			showAlertDialog("邮件发送成功!",function(){
				doHistoryBack();
				setTimeout(function(){
					checkIsSubmitAndGoBack();
				},1000);
				resetAndSearch();
			},true)
		}
	}
}

function checkRequired(){
	var isInternal = $("#isInternal").val();
	var label = "";
	if($("#subject").val()==""){
		label = ", 主题 ";
	}
	if(isInternal==1){
		if($("#internalto").val()==""&&$("#internaltodpid").val()==""&&$("#internaltoall").val()==""){
			label += ", 收件人 ";
		}
	}else{
		if($("#to_input").val()!=""){
			setValueByInput(autoComplete1);
		}
		if($("#cc_input").val()!=""){
			setValueByInput(autoComplete2);
		}
		if($("#bcc_input").val()!=""){
			setValueByInput(autoComplete3);
		}
		var emailDiv = $("#to_div .emailDiv");
		if(emailDiv.length==0){
			label += ", 收件人 ";
		}
	}
	$("#mouldtexteditor .EmailNew_fengeinput").remove();
	//$("#mouldtexteditor .colour").remove();
	
	$("#mouldtext").val(SQEditor.getHTML());
	if($("#mouldtext").val()==""||$("#mouldtexteditor").html()=="<p class=\"paragraph\"><br></p>"){
		label += ", 内容 ";
	}
	var f = false;
	if(label!=""){
		label = label.substring(1);
		showAlertDialog("必填项不能为空["+label+"]",function(){
			$("#btnFooterEdit").removeClass("issubmiting");
		},true)
	}else{
		f = true;
	}
	return f;
}


function changeMainListData(cid, propertyName, propertyValue){
	var mainListData = localStorage.getItem(itemKey);
	if(mainListData != null){
		mainListData = JSON.parse(mainListData);
		var data = mainListData["data"];
		var datas = data["datas"];
		for(var i = 0; i < datas.length; i++){
			var da = datas[i];
			var id = da["id"];
			if(id == cid){
				da[propertyName] = propertyValue;
				break;
			}
		}
		localStorage.setItem(itemKey, JSON.stringify(mainListData));
	}
}

function loadListByPageLoad(){
	var mainListData = localStorage.getItem(itemKey);
	if(mainListData != null){
		mainListData = JSON.parse(mainListData);
		var _userid = mainListData["userid"];
		if(_userid == userid){
			var data = mainListData["data"];
			var navUl = $("#navUl");
			var currentpanelid = navUl.attr("currentpanelid");
			bulidList(data,currentpanelid);
			rehreshScrollByGroup(1);
			var timestmp = mainListData["timestmp"];
			var nowTimestmp = new Date().getTime();
			var timeout = 1000 * 60 * 60 * 2;	//2小时
			var between = nowTimestmp - timestmp;
			if(between > timeout){
				autoRefreshList();
			}
		}else{	//用户改变了，重新缓存数据
			resetAndSearch();
		}
	}else{
		resetAndSearch();
	}
}

function autoRefreshList(){
	if(mainListScroll1){
		mainListScroll1.scrollTo(0,0);
		var pullDownObj = document.getElementById('pullDown1');
		pullDownObj.className = 'loading';
		pullDownObj.querySelector('.pullDownLabel').innerHTML = '正在刷新...';
	}
	resetAndSearch();
}

function isRunInEmobile(){
	return true;
}

/**
 * 根据当前列表，找到并显示对应的批量菜单
 */
function showBatchMenu(eve){
	var currentPanel = $(".currentPanel");
	var groupid = currentPanel.attr("id").replace("mainList_","");
	var panel = $("#listpanel"+groupid);
	$("[is_swiped='true']",panel).trigger("swipeRight");
	if(groupid>0){
		var popMenu = $("#batchMenu1");
		if(groupid==4){//垃圾箱
			$("#batchMenu1 ul li").show();
			$("#batchMenu1 .del").hide();
		}else if(groupid==7){//联系人
			$("#batchMenu1 ul li").hide();
			$("#batchMenu1 ul li.new").show();
		}else{
			$("#batchMenu1 ul li").show();
			$("#batchMenu1 .delforever").hide();
		}
		if(!popMenu.hasClass("active")){
			popMenu.addClass("active")
		}else{
			popMenu.removeClass("active")
		}
	}
	document.addEventListener( "click", hideBatchMenu );
	eve.stopPropagation();
}

/**
 * 隐藏批量菜单
 */
function hideBatchMenu(){
	var f = false;
	if($(".pop_menu.active").length>0){
		document.removeEventListener("click", hideBatchMenu );
		$(".pop_menu").removeClass("active");
		f = true;
	}
	return f;
}

function hideConfirmDialog(){
	$(".confirmDialog").addClass("hide");
	$("#footerBg").addClass("hide");
}

function hideAlertDialog(){
	$(".alertDialog").addClass("hide");
	$("#footerBg").addClass("hide");
}

function showAlertDialog(msg,okFun,isShowOKBtn,title){
	var alertDialog = $(".alertDialog");
	var top = ($(window).height()-160)/2;
	alertDialog.css("top",top+"px");
	$(".content",alertDialog).html(msg);
	if(!title){
		title = "提示";
	}
	$(".title",alertDialog).html(title);
	alertDialog.removeClass("hide");
	$("#footerBg").removeClass("hide");
	if(isShowOKBtn){
		$(".buttons",alertDialog).show();
		$(".okbtn",alertDialog)[0].onclick = function(){
			alertDialog.addClass("hide");
			$("#footerBg").addClass("hide");
			if(typeof(okFun)=="function"){
				okFun.call(this);
			}
		}
	}else{
		$(".buttons",alertDialog).hide();
	}
}

function showConfirmDialog(msg,okFun,cancelFun){
	var confirmDialog = $(".confirmDialog");
	var top = ($(window).height()-160)/2;
	confirmDialog.css("top",top+"px");
	$(".content",confirmDialog).html(msg);
	confirmDialog.removeClass("hide");
	$("#footerBg").removeClass("hide");
	$(".okbtn",confirmDialog)[0].onclick = function(){
		confirmDialog.addClass("hide");
		$("#footerBg").addClass("hide");
		if(typeof(okFun)=="function"){
			okFun.call(this);
		}
	}
	$(".cancelbtn",confirmDialog)[0].onclick = function(){
		confirmDialog.addClass("hide");
		$("#footerBg").addClass("hide");
		if(typeof(cancelFun)=="function"){
			cancelFun.call(this);
		}
	}
}

function toShowSearch(){
	if(checkLeftIsOpen()){
		return;
	}
	//重置搜索条件
	$("[name=fieldname_title]").val("");
	$("[name=fieldname_from]").val("");
	$("[name=fieldname_to]").val("");
	$("#status li").removeClass("checked");
	$("#startdate").val("");
	$("#enddate").val("");
	$(".del").hide();
	
	pushHistoryState({url:"a"});
	var navUl = $("#navUl");
	var currentpanelid = navUl.attr("currentpanelid");
	var groupid = currentpanelid.replace("mainList_","");
	
	$("#searchDiv").removeClass("hide");
	if(!$(".currentPanel").hasClass("hideLeft")){
		$(".currentPanel").addClass("hideLeft");
		$(".pageHeader").addClass("hideLeft");
	}
}


function initDateTime(theId){
	var obj = $("#"+theId);
	var htmlType = obj.attr("htmlType");//2.日期，3.时间
	if(htmlType == "2" || htmlType == "3" ){
		var currYear = (new Date()).getFullYear();	
		var opt={};
		opt.date = {preset : 'date', dateFormat : "yy-mm-dd"};
		opt.datetime = {preset : 'datetime', width : 40};
		opt.time = {preset : 'time'};
		opt.defa = {
			theme: 'android-ics light', //皮肤样式
	        display: 'modal', //显示方式 
	        mode: 'scroller', //日期选择模式
			lang:'zh',
	        startYear:currYear - 10, //开始年份
	        endYear:currYear + 10 //结束年份
		};
		
		if(htmlType == "2"){
			var optCurr = $.extend(opt['date'], opt['defa']);
			obj.mobiscroll(optCurr).date(optCurr);
		}else if(htmlType == "3"){
			var optCurr = $.extend(opt['time'], opt['defa']);
			obj.mobiscroll(optCurr).time(optCurr);
		}
		
		obj.change(function(){
			var p = $(obj).parent();
			var del = $(".del",p);
			if(del.length==0){
				p.append("<div class='del' onclick=\"delDate(this,'"+theId+"')\"></div>");
			}
			if(obj.val()==""){
				del.hide();
			}else{
				del.show();
			}
		});
	}
};

function delDate(obj,theId){
	$("#"+theId).val("");
	$(obj).hide();
}

function showAllSendTo(obj){
	var allname = $("#sendToAllName").html();
	var p = $(obj).parent();
	var w = $("#detailContent").width()-30;
	p.html("<div style='width:"+w+"px;word-wrap:break-word;'>"+allname+"</div>");
}

function showAllSendTo(obj,toWho){
	var allname = $("#"+toWho).html();
	var p = $(obj).parent();
	var w = $("#detailContent").width()-30;
	p.html("<div style='width:"+w+"px;word-wrap:break-word;'>"+allname+"</div>");
}

